
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>TypeScript 高级技巧 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,原文地址
前言用了一段时间的 typescript 之后，深感中大型项目中 typescript 的必要性，它能够提前在编译期避免许多 bug，如很恶心的拼写问题。而越来越多的 package 也开,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">TypeScript 高级技巧</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                June 12, 2019
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2019/06/12/Ts/TypeScript-%E9%AB%98%E7%BA%A7%E6%8A%80%E5%B7%A7/" title="TypeScript 高级技巧" class="">TypeScript 高级技巧</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    23k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    21 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Ts/" rel="tag">Ts</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <p><a href="https://juejin.im/post/5cffb431f265da1b7401f466?utm_source=gold_browser_extension" target="_blank" rel="noopener">原文地址</a></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>用了一段时间的 typescript 之后，深感中大型项目中 typescript 的必要性，它能够提前在编译期避免许多 bug，如很恶心的拼写问题。而越来越多的 package 也开始使用 ts，学习 ts 已是势在必行。</p>
<h2 id="01-keyof"><a href="#01-keyof" class="headerlink" title="01 keyof"></a>01 keyof</h2><p><code>keyof</code> 与 <code>Object.keys</code> 略有相似，只不过 <code>keyof</code> 取 <code>interface</code> 的键。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">interface Point &#123;</span><br><span class="line">    x: number;</span><br><span class="line">    y: number;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// type keys = "x" | "y"</span></span><br><span class="line">type keys = keyof Point;</span><br></pre></td></tr></table></figure>
<p>假设有一个 <code>object</code> 如下所示，我们需要使用 typescript 实现一个 get 函数来获取它的属性值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = &#123;</span><br><span class="line">  a: <span class="number">3</span>,</span><br><span class="line">  hello: <span class="string">'world'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">o: object, name: string</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> o[name]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们刚开始可能会这么写，不过它有很多缺点<br>1.无法确认返回类型：这将损失 ts 最大的类型校验功能<br>2.无法对 key 做约束：可能会犯拼写错误的问题</p>
<p>这时可以使用 <code>keyof</code> 来加强 <code>get</code> 函数的类型功能，有兴趣的同学可以看看 <code>_.get</code> 的 <code>type</code> 标记以及实现</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function get&lt;T extends object, K extends keyof T&gt;(o: T, name: K): T[K] &#123;</span><br><span class="line">  <span class="keyword">return</span> o[name]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="02-Partial-amp-Pick"><a href="#02-Partial-amp-Pick" class="headerlink" title="02 Partial &amp; Pick"></a>02 Partial &amp; Pick</h2><p>既然了解了 <code>keyof</code>，可以使用它对属性做一些扩展， 如实现 <code>Partial</code> 和 <code>Pick</code>，<code>Pick</code> 一般用在 <code>_.pick</code> 中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">type Partial&lt;T&gt; = &#123;</span><br><span class="line">  [P <span class="keyword">in</span> keyof T]?: T[P];</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">type Pick&lt;T, K extends keyof T&gt; = &#123;</span><br><span class="line">  [P <span class="keyword">in</span> K]: T[P];</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">interface User &#123;</span><br><span class="line">  id: number;</span><br><span class="line">  age: number;</span><br><span class="line">  name: string;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于: type PartialUser = &#123; id?: number; age?: number; name?: string; &#125;</span></span><br><span class="line">type PartialUser = Partial&lt;User&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于: type PickUser = &#123; id: number; age: number; &#125;</span></span><br><span class="line">type PickUser = Pick&lt;User, <span class="string">"id"</span> | <span class="string">"age"</span>&gt;</span><br></pre></td></tr></table></figure>
<h2 id="03-Condition-Type"><a href="#03-Condition-Type" class="headerlink" title="03 Condition Type"></a>03 Condition Type</h2><p>类似于 js 中的 <code>?:</code> 运算符，可以使用它扩展一些基本类型</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">T extends U ? X : Y</span><br><span class="line"></span><br><span class="line">type isTrue&lt;T&gt; = T extends <span class="literal">true</span> ? <span class="literal">true</span> : <span class="literal">false</span></span><br><span class="line"><span class="comment">// 相当于 type t = false</span></span><br><span class="line">type t = isTrue&lt;number&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于 type t = false</span></span><br><span class="line">type t1 = isTrue&lt;<span class="literal">false</span>&gt;</span><br></pre></td></tr></table></figure>
<h2 id="04-never-amp-Exclude-amp-Omit"><a href="#04-never-amp-Exclude-amp-Omit" class="headerlink" title="04 never &amp; Exclude &amp; Omit"></a>04 never &amp; Exclude &amp; Omit</h2><p>官方文档对 <code>never</code> 的描述如下</p>
<blockquote>
<p>the never type represents the type of values that never occur.</p>
</blockquote>
<p>结合 <code>never</code> 与 <code>conditional type</code> 可以推出很多有意思而且实用的类型，比如 <code>Omit</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">type Exclude&lt;T, U&gt; = T extends U ? never : T;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于: type A = 'a'</span></span><br><span class="line">type A = Exclude&lt;<span class="string">'x'</span> | <span class="string">'a'</span>, <span class="string">'x'</span> | <span class="string">'y'</span> | <span class="string">'z'</span>&gt;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>结合 <code>Exclude</code> 可以推出 <code>Omit</code> 的写法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">type Omit&lt;T, K extends keyof any&gt; = Pick&lt;T, Exclude&lt;keyof T, K&gt;&gt;;</span><br><span class="line"></span><br><span class="line">interface User &#123;</span><br><span class="line">  id: number;</span><br><span class="line">  age: number;</span><br><span class="line">  name: string;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于: type PickUser = &#123; age: number; name: string; &#125;</span></span><br><span class="line">type OmitUser = Omit&lt;User, <span class="string">"id"</span>&gt;</span><br></pre></td></tr></table></figure>
<h2 id="05-typeof"><a href="#05-typeof" class="headerlink" title="05 typeof"></a>05 typeof</h2><p>顾名思义，<code>typeof</code> 代表取某个值的 <code>type</code>，可以从以下示例来展示他们的用法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> a: number = <span class="number">3</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于: const b: number = 4</span></span><br><span class="line"><span class="keyword">const</span> b: <span class="keyword">typeof</span> a = <span class="number">4</span></span><br></pre></td></tr></table></figure>
<p>在一个典型的服务端项目中，我们经常需要把一些工具塞到 <code>context</code> 中，如<code>config</code>，<code>logger</code>，<code>db models</code>, <code>utils</code> 等，此时就使用到 <code>typeof</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> logger <span class="keyword">from</span> <span class="string">'./logger'</span></span><br><span class="line"><span class="keyword">import</span> utils <span class="keyword">from</span> <span class="string">'./utils'</span></span><br><span class="line"></span><br><span class="line">interface Context extends KoaContect &#123;</span><br><span class="line">  logger: <span class="keyword">typeof</span> logger,</span><br><span class="line">  utils: <span class="keyword">typeof</span> utils</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">app.use(<span class="function">(<span class="params">ctx: Context</span>) =&gt;</span> &#123;</span><br><span class="line">  ctx.logger.info(<span class="string">'hello, world'</span>)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 会报错，因为 logger.ts 中没有暴露此方法，可以最大限度的避免拼写错误</span></span><br><span class="line">  ctx.loger.info(<span class="string">'hello, world'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="06-is"><a href="#06-is" class="headerlink" title="06 is"></a>06 is</h2><p>在此之前，先看一个 koa 的错误处理流程，以下是对 error 进行集中处理，并且标识 code 的过程</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">app.use(<span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">await</span> next();</span><br><span class="line">  &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">    <span class="keyword">let</span> code = <span class="string">'BAD_REQUEST'</span></span><br><span class="line">    <span class="keyword">if</span> (err.isAxiosError) &#123;</span><br><span class="line">      code = <span class="string">`Axios-<span class="subst">$&#123;err.code&#125;</span>`</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (err <span class="keyword">instanceof</span> Sequelize.BaseError) &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    ctx.body = &#123;</span><br><span class="line">      code</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>在 <code>err.code</code> 处，会编译出错，提示 Property ‘code’ does not exist on type ‘Error’.ts(2339)。</p>
<p>此时可以使用 <code>as AxiosError</code> 或者 <code>as any</code> 来避免报错，不过强制类型转换也不够友好</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> ((err <span class="keyword">as</span> AxiosError).isAxiosError) &#123;</span><br><span class="line">  code = <span class="string">`Axios-<span class="subst">$&#123;(err <span class="keyword">as</span> AxiosError).code&#125;</span>`</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时可以使用 is 来判定值的类型</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isAxiosError</span> (<span class="params">error: any</span>): <span class="title">error</span> <span class="title">is</span> <span class="title">AxiosError</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> error.isAxiosError</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (isAxiosError(err)) &#123;</span><br><span class="line">  code = <span class="string">`Axios-<span class="subst">$&#123;err.code&#125;</span>`</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 <code>GraphQL</code> 的源码中，有很多诸如此类的用法，用以标识类型</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">isType</span>(<span class="params">type: any</span>): <span class="title">type</span> <span class="title">is</span> <span class="title">GraphQLType</span>;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">export</span> <span class="title">function</span> <span class="title">isScalarType</span>(<span class="params">type: any</span>): <span class="title">type</span> <span class="title">is</span> <span class="title">GraphQLScalarType</span>;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">export</span> <span class="title">function</span> <span class="title">isObjectType</span>(<span class="params">type: any</span>): <span class="title">type</span> <span class="title">is</span> <span class="title">GraphQLObjectType</span>;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">export</span> <span class="title">function</span> <span class="title">isInterfaceType</span>(<span class="params">type: any</span>): <span class="title">type</span> <span class="title">is</span> <span class="title">GraphQLInterfaceType</span>;</span></span><br></pre></td></tr></table></figure>
<h2 id="07-interface-amp-type"><a href="#07-interface-amp-type" class="headerlink" title="07 interface &amp; type"></a>07 interface &amp; type</h2><p>interface 与 type 的区别是什么？可以参考以下 stackoverflow 的问题</p>
<p><a href="https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types" target="_blank" rel="noopener">https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types</a></p>
<p>一般来说，<code>1</code>interface<code>与</code>type` 区别很小，比如以下两种写法差不多</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">interface A &#123;</span><br><span class="line">  a: number;</span><br><span class="line">  b: number;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">type B &#123;</span><br><span class="line">  a: number;</span><br><span class="line">  b: number;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中 interface 可以如下合并多个，而 type 只能使用 &amp; 类进行连接。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">interface A &#123;</span><br><span class="line">    a: number;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">interface A &#123;</span><br><span class="line">    b: number;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> a: A = &#123;</span><br><span class="line">    a: <span class="number">3</span>,</span><br><span class="line">    b: <span class="number">4</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="08-Dictionary-amp-Many"><a href="#08-Dictionary-amp-Many" class="headerlink" title="08 Dictionary &amp; Many"></a>08 Dictionary &amp; Many</h2><p>这几个语法糖是从 <code>lodash</code> 的 <code>types</code> 源码中学到的，平时工作中的使用频率还挺高。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">interface Dictionary&lt;T&gt; &#123;</span><br><span class="line">  [index: string]: T;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">interface NumericDictionary&lt;T&gt; &#123;</span><br><span class="line">  [index: number]: T;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> data:Dictionary&lt;number&gt; = &#123;</span><br><span class="line">  a: <span class="number">3</span>,</span><br><span class="line">  b: <span class="number">4</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="09-使用-const-enum-维护常量表"><a href="#09-使用-const-enum-维护常量表" class="headerlink" title="09 使用 const enum 维护常量表"></a>09 使用 const enum 维护常量表</h2><p>相比使用字面量对象维护常量，const enum 可以提供更安全的类型检查</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用 object 维护常量</span></span><br><span class="line"><span class="keyword">const</span> enum TODO_STATUS &#123;</span><br><span class="line">    TODO = <span class="string">'TODO'</span>,</span><br><span class="line">    DONE = <span class="string">'DONE'</span>,</span><br><span class="line">    DOING = <span class="string">'DOING'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用 const enum 伟华常量</span></span><br><span class="line"><span class="keyword">const</span> enum TODO_STATUS &#123;</span><br><span class="line">    TODO = <span class="string">'TODO'</span>,</span><br><span class="line">    DONE = <span class="string">'DONE'</span>,</span><br><span class="line">    DOING = <span class="string">'DOING'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function todos (status: TODO_STATUS): Todo[];</span><br><span class="line"></span><br><span class="line">todos(TODO_STATUS.TODO)</span><br></pre></td></tr></table></figure>
<h2 id="10-VS-Code-Tips-amp-Typescript-Command"><a href="#10-VS-Code-Tips-amp-Typescript-Command" class="headerlink" title="10 VS Code Tips &amp; Typescript Command"></a>10 VS Code Tips &amp; Typescript Command</h2><p>使用 VS Code 有时会出现，使用 tsc 编译时产生的问题与 vs code 提示的问题不一致</p>
<p>找到项目右下角的 Typescript 字样，右侧显示它的版本号，可以点击选择 Use Workspace Version，它表示与项目依赖的 typescript 版本一直。</p>
<p>或者编辑 <code>.vs-code/settings.json</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"typescript.tsdk"</span>: <span class="string">"node_modules/typescript/lib"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="11-Typescript-Roadmap"><a href="#11-Typescript-Roadmap" class="headerlink" title="11 Typescript Roadmap"></a>11 Typescript Roadmap</h2><p>最后一条也是最重要的一条，翻阅 Roadmap，了解 ts 的一些新的特性与 bug 修复情况。</p>
<p><a href="https://github.com/Microsoft/TypeScript/wiki/Roadmap" target="_blank" rel="noopener">Typescript Roadmap</a></p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#01-keyof"><span class="toc-number">1.1.</span> <span class="toc-text">01 keyof</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#02-Partial-amp-Pick"><span class="toc-number">1.2.</span> <span class="toc-text">02 Partial &amp; Pick</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#03-Condition-Type"><span class="toc-number">1.3.</span> <span class="toc-text">03 Condition Type</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#04-never-amp-Exclude-amp-Omit"><span class="toc-number">1.4.</span> <span class="toc-text">04 never &amp; Exclude &amp; Omit</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#05-typeof"><span class="toc-number">1.5.</span> <span class="toc-text">05 typeof</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#06-is"><span class="toc-number">1.6.</span> <span class="toc-text">06 is</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#07-interface-amp-type"><span class="toc-number">1.7.</span> <span class="toc-text">07 interface &amp; type</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#08-Dictionary-amp-Many"><span class="toc-number">1.8.</span> <span class="toc-text">08 Dictionary &amp; Many</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#09-使用-const-enum-维护常量表"><span class="toc-number">1.9.</span> <span class="toc-text">09 使用 const enum 维护常量表</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-VS-Code-Tips-amp-Typescript-Command"><span class="toc-number">1.10.</span> <span class="toc-text">10 VS Code Tips &amp; Typescript Command</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11-Typescript-Roadmap"><span class="toc-number">1.11.</span> <span class="toc-text">11 Typescript Roadmap</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
